from datetime import timedelta

from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required
from flask_wtf import CSRFProtect
from werkzeug.security import generate_password_hash
from extension import db
from models.models import UserModel
from .form import RegisterForm
bp=Blueprint('user',__name__,url_prefix='/user')

@bp.route('/login',methods=['GET','POST'])
def login():
    # 1判断输入是否合法————————调用api直接判断，最好别用那个狗屁表单校验器,另外有些非空校验放在前端做好，免得发来发去的
    data = request.get_json()
    username = data.get('username').strip()
    password = data.get('password').strip()
    if username is None or len(username) == 0:
        return jsonify({"message": "账号不能为空", "code": 201, "data": None})
    if password is None or len(password) == 0:
        return jsonify({"message": "密码不能为空", "code": 201, "data": None})
    # 2判断数据库是否有信息
    user = UserModel.query.filter_by(username=username).first()
    if user is None:
        return jsonify({"message": "用户不存在", "code": 201, "data": None})
    # 3验证账号密码是否匹配
    # hashed_password = user.password.encode('utf-8')
    # input_password = password.encode('utf-8')
    # if not bcrypt.checkpw(input_password, hashed_password):
    #     return jsonify({"message": "密码错误", "code": 201, "data": None})
    if user.password != password:
        return jsonify({"message": "密码错误", "code": 201, "data": None})
    # 4 用户登录成功后将用户信息保存在token中，返回前端，前端存起来后续需要时发到后端进行验证
    #!!!!!!!!!注意： 这里放的字段是你后面要拿出来用到字段，不放后面也拿不出来
    access_token=create_access_token(identity=username)
    return jsonify({"message": "登录成功", "code": 200, "token":access_token})



#提交表单数据或跳转注册页面
@bp.route('/register',methods=['GET','POST'])
def register():
   # 验证用户提交的邮箱和验证码是否对应且正确
   #表单验证：fLask-wtf
   if request.method=='GET':
       #进行视图渲染
       return "你在干什么？"
   else:
       # 后端进行表单验证
       form=RegisterForm(request.form)
       if form.validate():
            username=form.username.data
            password=form.password.data
            User = UserModel(username=username,password=password)
            #密码加密
            # User =UserModel(username=username, password=generate_password_hash(password))
            db.session.add(User)
            db.session.commit()
            return jsonify({"code": 200, "message": "注册成功！"})
            #提示注册成功
            #重定向到登录页面
       else:
           print(form.errors)
           return jsonify({"code": 400, "message": str(form.errors["password"])})





